﻿using System;
using System.Diagnostics;
using System.Web;

namespace CodeContrib.Web
{
	public static class UrlExtensions
	{
		[DebuggerStepThrough]
		public static string ToSubdomain(this Uri url)
		{
			if (url.HostNameType
			    == UriHostNameType.Dns)
			{
				var host = url.Host;

				if (host.Split('.').Length > 2)
				{
					var lastIndex = host.LastIndexOf(".");
					var index = host.LastIndexOf(".", lastIndex - 1);

					return host.Substring(0, index);
				}
			}

			return null;
		}

		[DebuggerStepThrough]
		public static string VerifyUrlProtocol(this string url)
		{
			return VerifyUrlProtocol(url, false);
		}

		[DebuggerStepThrough]
		public static string VerifyUrlProtocol(this string url, bool forceSecure)
		{
			if (string.IsNullOrEmpty(url))
			{
				return null;
			}

			if (!url.StartsWith("http"))
			{
				return url;
			}

			var uriBuilder = new UriBuilder(url);
			uriBuilder.Scheme = (forceSecure || HttpContext.Current.Request.IsSecureConnection) ? "https" : "http";

			return uriBuilder.Uri.ToString();
		}
	}
}